import { createContext, useRef, ReactNode, FC, useState, PropsWithChildren, cloneElement, ReactElement, useEffect } from 'react';

interface KeepAliteContext {
  childrenReactNode?: HTMLElement | null;
  collectReactNode: (reactNode: ReactElement) => void;
}

export const KeepAliteContext = createContext<KeepAliteContext>({} as KeepAliteContext);

export default function Provider({ children }: { children: ReactNode }) {

  const ref = useRef(null)

  const [childReactNode, setChildReactNode] = useState<ReactElement>()

  const collectReactNode = (reactNode: ReactElement) =>setChildReactNode(reactNode)

  const [contentValues, setContentValues] = useState<KeepAliteContext>({ childrenReactNode: ref.current, collectReactNode })

  useEffect(() => {
    const contextValue = { childrenReactNode: ref.current, collectReactNode }
    setContentValues(contextValue)
  }, [childReactNode])

  return (
    <div>
      <div ref={ref}> {childReactNode}</div>
      <KeepAliteContext.Provider value={contentValues}> {children}</KeepAliteContext.Provider>
    </div>
  )
}


